package com.media.yuvplayer;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapRegionDecoder;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.media.yuvplayer.utils.OpenCVUtils;
import com.media.yuvplayer.utils.YuvUtils;

import org.opencv.android.Utils;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends AppCompatActivity implements View.OnClickListener,
        EasyPermissions.PermissionCallbacks, EasyPermissions.RationaleCallbacks {

    private static final String TAG = MainActivity.class.getSimpleName();
    private ImageView mI420ToRgbIv;
    private YuvUtils mYuvUtils;
    private OpenCVUtils mOpenCvUitls;

    static {
        System.loadLibrary("opencv_jni");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.btn_format_setting).setOnClickListener(this);

        mYuvUtils = new YuvUtils();

        // Example of a call to a native method
        TextView tv = (TextView) findViewById(R.id.sample_text);
        tv.setText("hello world");
        findViewById(R.id.btn_load_yuv).setOnClickListener(this);

        mI420ToRgbIv = findViewById(R.id.iv_test1);


        mOpenCvUitls = new OpenCVUtils();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_format_setting:
                Intent intent = new Intent(this, YuvPreferenceActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_load_yuv:
                if (!hasStoragePermission()) {
                    EasyPermissions.requestPermissions(this, "Need write something to SDCard.", AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                    return;
                }
                final InputStream inputStream = getResources().openRawResource(R.raw.t1280_720);
                try {
                    byte[] src = new byte[inputStream.available()];
                    inputStream.read(src);
                    inputStream.close();
//                    byte[] bytes = mYuvUtils.I420ToRGB24(src, 1280, 720);
                    int width = 500;
                    int height = 500;
                    byte[] bytes = YuvUtils.nativeCrop(src, 1280, 720, 0, 0, width, height);
                    Mat mat = new Mat(new Size(width , height), CvType.CV_8UC4);
                    mat.put(0, 0, bytes);
                    Imgproc.cvtColor(mat,mat,Imgproc.COLOR_BGRA2RGBA);
                    Bitmap bm = Bitmap.createBitmap(width, width, Bitmap.Config.ARGB_8888);
                    Utils.matToBitmap(mat, bm);
                    mI420ToRgbIv.setImageBitmap(bm);
                } catch (IOException e) {
                    e.printStackTrace();
                }


                break;
        }
    }

    private boolean hasStoragePermission() {
        return EasyPermissions.hasPermissions(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }


    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        Log.d(TAG, "onPermissionsGranted:" + requestCode + ":" + perms.size());
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        Log.d(TAG, "onPermissionsDenied:" + requestCode + ":" + perms.size());

        // (Optional) Check whether the user denied any permissions and checked "NEVER ASK AGAIN."
        // This will display a dialog directing them to enable the permission in app settings.
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }


    @Override
    public void onRationaleAccepted(int requestCode) {
        Log.d(TAG, "onRationaleAccepted:" + requestCode);
    }

    @Override
    public void onRationaleDenied(int requestCode) {
        Log.d(TAG, "onRationaleDenied:" + requestCode);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {

            // Do something after user returned from app settings screen, like showing a Toast.
            Log.d(TAG, "Do something after user returned from app settings screen, like showing a Toast.");
        }
    }

}
